package org.phoenix.mall.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.phoenix.mall.admin.common.pojo.bo.RoleBO;
import org.phoenix.mall.admin.common.pojo.vo.RightVO;
import org.phoenix.mall.admin.common.pojo.vo.RoleVO;
import org.phoenix.mall.admin.common.utils.PhoenixResponseJSON;
import org.phoenix.mall.admin.config.annotations.AuthRequired;
import org.phoenix.mall.admin.pojo.Role;
import org.phoenix.mall.admin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(value = "角色管理", tags = {"角色管理API"})
@RestController
@RequestMapping("roles")
@AuthRequired
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "获取角色列表", notes = "获取角色列表", httpMethod = "GET")
    @GetMapping("")
    public PhoenixResponseJSON list() {
        List<RoleVO> list = roleService.getRoleList();
        return PhoenixResponseJSON.ok(list);
    }

    @ApiOperation(value = "添加角色", notes = "添加角色", httpMethod = "POST")
    @PostMapping("")
    public PhoenixResponseJSON add(@RequestBody RoleBO roleBO) {
        Role role = new Role();
        role.setRoleName(roleBO.getRoleName());
        role.setRoleDesc(roleBO.getRoleDesc());
        role.setCreateTime(new Date());

        Role persisRole = roleService.createRole(role);

        return PhoenixResponseJSON.ok(persisRole);
    }

    @ApiOperation(value = "配置权限", notes = "配置权限", httpMethod = "POST")
    @PostMapping("/{roleId}/rights")
    public PhoenixResponseJSON grant(@PathVariable Integer roleId, @RequestBody Map<String, Object> map) {
        Object objParam = map.get("rids");
        if(objParam == null) {
            return PhoenixResponseJSON.errorMsg("缺少参数：权限ID列表");
        }
        String[] rids = objParam.toString().split(",");
        List<RightVO> list = roleService.grantRoleRights(roleId, rids);
        return PhoenixResponseJSON.ok(list);
    }

    @ApiOperation(value = "删除权限", notes = "删除权限", httpMethod = "DELETE")
    @DeleteMapping("/{roleId}/rights/{rightId}")
    public PhoenixResponseJSON delete(@PathVariable Integer roleId, @PathVariable Integer rightId) {
        List<RightVO> list = roleService.deleteRights(roleId, rightId);
        return PhoenixResponseJSON.ok(list);
    }

    @ApiOperation(value = "获取角色权限列表", notes = "获取角色权限列表", httpMethod = "GET")
    @GetMapping("/{roleId}/rights")
    public PhoenixResponseJSON get(@PathVariable Integer roleId) {
        List<RightVO> list = roleService.getRightsById(roleId);
        return PhoenixResponseJSON.ok(list);
    }

}
